package org.keyroy.tag;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class KFile {

	public static final String getString(InputStream inputStream) {
		return new String(getBytes(inputStream));
	}

	public static final String byte2String(byte b) {
		StringBuffer stringBuffer = new StringBuffer("0x");
		int low = b & 0xF;
		int high = (b >> 8) & 0xF;
		stringBuffer.append(Character.forDigit(high, 16));
		stringBuffer.append(Character.forDigit(low, 16));

		return stringBuffer.toString().toUpperCase();
	}

	public static final String getString(InputStream inputStream, String encode) {
		try {
			return new String(getBytes(inputStream), encode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static final byte[] getBytes(InputStream inputStream, ReadListener readListener) {
		try {
			int bufferSize = 1024;
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bufferSize);
			byte[] buffer = new byte[bufferSize];
			int length = 0;
			while ((length = inputStream.read(buffer)) > 0) {
				byteArrayOutputStream.write(buffer, 0, length);
				readListener.onRead(byteArrayOutputStream.size());
			}
			buffer = byteArrayOutputStream.toByteArray();
			inputStream.close();
			byteArrayOutputStream.close();
			return buffer;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static final byte[] getBytes(InputStream inputStream) {
		try {
			int bufferSize = inputStream.available();
			bufferSize = Math.max(bufferSize, 1024 * 50);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bufferSize);
			byte[] buffer = new byte[bufferSize];
			int length = 0;
			while ((length = inputStream.read(buffer)) > 0) {
				byteArrayOutputStream.write(buffer, 0, length);
			}
			buffer = byteArrayOutputStream.toByteArray();
			inputStream.close();
			byteArrayOutputStream.close();
			return buffer;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public interface ReadListener {
		public void onRead(long current);
	}

}
